<template>
  <el-upload v-model:file-list="fileList" class="upload-demo" :action="uploadFile" multiple
    :on-preview="handlePreview" :on-success="handleSuccess" :on-remove="handleRemove" :before-remove="beforeRemove"
    :limit="3" :on-exceed="handleExceed">
    <el-button type="primary">Click to upload</el-button>
    <template #tip>
      <div class="el-upload__tip">
        jpg/png files with a size less than 500KB.
      </div>
    </template>
  </el-upload>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import baseUrl from '../../api/baseUrl'
import { listFile, deleteFileByFileObjectName } from '../../api/file-api';

const uploadFile = baseUrl + 'api/minio/uploadFile/'

const fileList = ref<UploadUserFile[]>([])

// 定义加载数据的函数
const loadData = () => {
  listFile().then((response) => {
    console.log('加载数据中...')
    response.forEach((item: any) => {
      fileList.value.push({
        name: item.name,
        url: item.url,
        response: item,
      })
    })
    // 增加一条数据到 fileList
    console.log('数据加载完成', fileList.value)
  })
}

// 使用 onMounted 钩子在组件加载时调用 loadData
onMounted(() => {
  loadData()
})

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  deleteFileByFileObjectName(file.response.fileObjectName).then(() => {
    ElMessage.success('Delete successfully')
  }).catch(() => {
    ElMessage.error('Delete failed')
  })
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  window.open(uploadFile.url);
}

const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile, uploadFiles) => {
  if (response.url && uploadFile.name.endsWith('.pdf')) {
    uploadFile.url = response.url;
  }
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
    } totally`
  )
}


const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}
</script>